﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace UpdateXml
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                UpdateXml(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private static void UpdateXml(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.WriteLine("please input command...");
                Console.WriteLine("{xmlPath} {xpath} node {attr} {value}");
                Console.WriteLine("{xmlPath} {xpath} value {value}");
                args = Console.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
            }
            if (args.Length < 3)
            {
                throw new ArgumentException("{xmlPath} {xpath} {value}");
            }
            var configPath = args[0];
            var xpath = args[1];
            var valType = args[2];
            var value = GetValue(args[3]);
            if (!File.Exists(configPath))
            {
                throw new ArgumentException(string.Format("file[{0}] no found", configPath));
            }
            var xml = new XmlDocument();
            xml.Load(configPath);
            var xmlNode = xml.SelectSingleNode(xpath);
            if (xmlNode == null)
            {
                throw new ArgumentException(string.Format("xml SelectSingleNode [{0}] no found", xpath));
            }
            switch (valType.ToLower())
            {
                case "node":
                    if (args.Length < 5)
                    {
                        throw new ArgumentException("{configPath} {xpath} node {attr} {value}");
                    }
                    var attr = args[3];
                    value = GetValue(args[4]);
                    var valAttr = xmlNode.Attributes[attr];
                    if (valAttr != null)
                    {
                        valAttr.Value = value;
                    }
                    else
                    {
                        Console.WriteLine(string.Format("xmlNode attr [{0}] no found", attr));
                    }
                    break;
                default:
                    xmlNode.Value = value;
                    break;
            }
            xml.Save(configPath);
            Console.WriteLine("save ok");
        }

        private static string GetValue(string value)
        {
            switch (value)
            {
                case "$DateTime$":
                    return DateTime.Now.ToString("yyyyMMddHHmmss");
                    break;
                case "$Date$":
                    return DateTime.Now.ToString("yyyyMMdd");
                    break;
            }
            return value;
        }
    }
}
